package model;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

import controller.Controller;

public class FlightGearModel implements Model {
	private Controller controller;
	private double[] orders;
	private Config config;
	private HashMap<String , Attribute> attMap;
	private String[] attArr; //array for saving the order of the attributes
	
 	private void saveConfig(String fileName){
		/*for Dev usage. in case of changing Config struct & need of changing the file Config.xml
		 * Saves (overwrites if needed) the Config object into filename,
		 * using XMLEncoder.
		 */
			XMLEncoder e;
			try {
				e = new XMLEncoder(new FileOutputStream(fileName));
				e.writeObject(config);
				e.close();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
			
	}
	@Override
	public void loadConfig(String fileName) {
		/*Loads a config object from fileName.*/
		try {
			XMLDecoder d = new XMLDecoder(new FileInputStream(fileName));
			//if not found - no need to close, so no need to insert "finally"
			config = (Config) d.readObject();
			d.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		/*Now, create a hashTable according to the XML file, and the Attributes field,
		 *  splitted by the delimiter
		 */
		
		attMap = new HashMap<String , Attribute>();
		
		/*Create an array of attribute names*/
		attArr = config.getAttributes().split(config.getDelimiter());
		for(String s: attArr){
			attMap.put(s, new Attribute(s, config.getAttributesHistoryLength()) );
		}
	}
	@Override
	public void setController(Controller controller) {
		this.controller = controller;
		System.out.println("Flight gear model says controller updated!");
	}
	@Override
	public void startModel() {
		/*Start the reader*/
		SimulatorReader simReader;
		try {
			simReader = new SimulatorReader(new BufferedReader(new FileReader(config.getFileName()))  , config.getDelimiter()  , attArr);
			simReader.startToRead(attMap , controller);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void updateFlightOrders(double[] orders) {
		this.orders = new double[orders.length];
		System.arraycopy(orders, 0, this.orders, 0, orders.length);
		System.out.println("Flight gear model says flight orders updated!");
	}
	@Override
	public void closeModel() {
		System.out.println("Flight gear model says closing model - though nothing here!");
	}

	
}
